<?php
/**
 * 采购合同文件（PDF）
 */
namespace App\Logic\Purchase;

use App\Exporter\Purchase\ContractExporter;
use App\Models\Purchase\PurchaseOrder;
use App\Models\Purchase\PurchaseOrderContract;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use SnappyPdf;
class CreatePOContract
{
    public static function handle($param)
    {
        ini_set('memory_limit', '200M');
        set_time_limit(0);
        $param['file_type'] == 1 ? self::_createPDFPurContract($param) : self::_createExcelPurContract($param);
    }

    /**
     * PDF合同文件
     * @param $param
     */
    private static function _createPDFPurContract($param){
        try{
            DB::beginTransaction();
            $purchase = self::_getPurchaseOrder($param['id']);
            $pdf = SnappyPdf::loadView('purchase.contract-create-pdf.index',compact('purchase','param'));
            //$pdf->setOption('default-font','Arial');
            //$pdf->setOption('font-weight','bold');
            $path = PurchaseOrderContract::getFile($purchase->purchase_no,1);
            $pdf->save($path);
            PurchaseOrderContract::storeFile($purchase->purchase_no,1);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * EXCEL合同文件
     * @param $param
     */
    private static function _createExcelPurContract($param){
        try{
            DB::beginTransaction();
            $purchase = self::_getPurchaseOrder($param['id']);
            $filename = PurchaseOrderContract::fileName($purchase->purchase_no,2);
            $path = PurchaseOrderContract::FILE_NAME_DIR.DIRECTORY_SEPARATOR.$filename;
            Excel::store(new ContractExporter($purchase,$param),$path);
            PurchaseOrderContract::storeFile($purchase->purchase_no,2);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     */
    private static function _getPurchaseOrder($id){
        return PurchaseOrder::query()->find($id);
    }
}
